﻿using FS_Model.Account;
using FS_Model.FileModel;
using FS_Unitys;
using FS_Unitys.Basic;
using FS_Unitys.Config;
using FS_Unitys.Extendsion;
using FS_Unitys.Log;
using Microsoft.VisualBasic.Devices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FS_Service
{
    public class FSService
    {
        private static readonly LogHelper LogHelper = new LogHelper(typeof(FSService));

        /// <summary>
        /// 从体检服务器读取文件写入到前置机
        /// </summary>
        /// <returns></returns>
        public ResultInfo WriteAbsoultePath(string resJson)
        {
            ResultInfo res = WritePath(resJson, ConfigManager.absolutePath, false);
            return res;
        }

        /// <summary>
        /// 写入到共享文件夹
        /// </summary>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public ResultInfo WriteNetWorkPath(string resJson)
        {
            ResultInfo res = WritePath(resJson, ConfigManager.networkAddress, true);
            return res;
        }

        /// <summary>
        /// 修改共享文件夹的内部文件名称
        /// </summary>
        /// <param name="dirFileName"></param>
        /// <returns></returns>
        public ResultInfo RenameFileNameSuffix(List<string> listDirFileName, bool isNetWork)
        {
            foreach (string dirFileName in listDirFileName)
            {
                string oldPathName = dirFileName;
                string newPathName = string.Empty;
                try
                {
                    if (isNetWork)
                    {
                        using (SharedTool tool = new SharedTool(ConfigManager.username, ConfigManager.password, ConfigManager.ip))
                        {
                            // 改名
                            newPathName = ConfigManager.networkAddress + ConfigManager.absolutebackwown + "\\" + Path.GetFileName(dirFileName) + ConfigManager.suffix;
                            //  \\192.168.0.113\shenglitongde\checkreport
                            LogHelper.Info($"oldPathName:{oldPathName},newPathName:{newPathName}");

                            File.Move(oldPathName, newPathName);
                        }
                    }
                    else
                    {
                        // Computer MyComputer = new Computer();

                        // string newFileName = Path.GetFileName(newPathName);
                        // 如果有了再改
                        // MyComputer.FileSystem.RenameFile(oldPathName, newFileName);
                        // File.Move(oldPathName, newPathName);
                        newPathName = ConfigManager.absolutePath + ConfigManager.absolutebackwown + "\\" + Path.GetFileName(dirFileName);
                        oldPathName = oldPathName.Replace("//", "\\");
                        LogHelper.Info($"oldPathName:{oldPathName},newPathName:{newPathName}");
                        File.Move(oldPathName, newPathName);

                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return CodeStatus.error_204.GetStatus(e.ToString());
                }

            }

            return CodeStatus.success.GetStatus();
        }


        public ResultInfo WritePath(string resJson, string basePath, bool isNetWork)
        {
            ResultInfo res = JsonXmlUtils.DeserializeObject<ResultInfo>(resJson);

            if (res.code != CodeStatus.success.GetHashCode())
                return res;

            string json = res.data.ToString();
            // 读取到数据，写入到本地
            List<ReadFileModel> list = JsonXmlUtils.DeserializeObject<List<ReadFileModel>>(json);

            List<string> listResult = new List<string>();
            foreach (ReadFileModel fileModel in list)
            {
                string dirFileName = fileModel.dirPath + "//" + fileModel.fileName;


                string path = basePath + dirFileName;

                string reNamePath = string.Empty;
                try
                {
                    // 写入的文件名称
                    if (isNetWork)
                    {
                        // 远程写入
                        using (SharedTool tool = new SharedTool(ConfigManager.username, ConfigManager.password, ConfigManager.ip))
                        {
                            File.WriteAllBytes(path, fileModel.fileBytes);
                        }

                        // reNamePath = ConfigManager.absolutePath + dirFileName;
                    }
                    else
                    {

                        path = path.Replace("\\\\", "\\");
                        // logHelper.Info("地址:" + path);
                        File.WriteAllBytes(path, fileModel.fileBytes);
                        // reNamePath = ConfigManager.absolutePath + dirFileName;
                    }

                    reNamePath = GteReversalBasePath(basePath) + dirFileName;

                    listResult.Add(reNamePath);
                    res.data = listResult;
                }
                catch (Exception e)
                {
                    //logHelper.Error(e.ToString());
                    Console.WriteLine(e);
                    return CodeStatus.error_202.GetStatus(e.ToString());
                }
            }

            return res;
        }

        /// <summary>
        ///如果是共享文件夹，就是绝对路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GteReversalBasePath(string path)
        {
            string result = string.Empty;
            if (path == ConfigManager.absolutePath)
                result = ConfigManager.networkAddress;
            else
                result = ConfigManager.absolutePath;

            return result;
        }


        ////////////////// 读取 ///////////////////////////////////////

        /// <summary>
        /// 从体检传到前置机
        /// </summary>
        /// <returns></returns>
        public ResultInfo ReadNetWorkToAbsolute()
        {
            List<ReadFileModel> list = ReadFile(ConfigManager.readDirs, ConfigManager.networkAddress, true);
            if (list.Count == 0)
                return CodeStatus.error_203.GetStatus();
            ResultInfo res = CodeStatus.success.GetStatus();
            res.data = list;
            return res;
        }

        /// <summary>
        /// 从前置机读取文件写入到共享文件夹
        /// </summary>
        /// <returns></returns>
        public ResultInfo ReadToAbsolute()
        {
            List<ReadFileModel> list = ReadFile(ConfigManager.wirteDirs, ConfigManager.absolutePath, false);
            if (list.Count == 0)
                return CodeStatus.error_203.GetStatus();

            list = list.Take(10).ToList();
            ResultInfo res = CodeStatus.success.GetStatus();
            res.data = list;
            return res;
        }

        public List<ReadFileModel> ReadFile(string[] dirs, string basePath, bool isNetWork)
        {
            string errorMsg = string.Empty;
            string[] readDirs = dirs;


            List<ReadFilePathModel> listFilePathModel = new List<ReadFilePathModel>();
            foreach (string readDir in readDirs)
            {
                ReadFilePathModel ReadFilePathModel = new ReadFilePathModel();
                ReadFilePathModel.readDir = readDir;
                string dir = basePath + readDir;
                //string[] filePaths = null;
                if (isNetWork)
                {
                    using (SharedTool tool = new SharedTool(
                        ConfigManager.username,
                        ConfigManager.password,
                        ConfigManager.ip))
                    {
                        ReadFilePathModel.listFilePath = Directory.GetFiles(dir)?.ToList();
                    }
                }
                else
                {
                    ReadFilePathModel.listFilePath = Directory.GetFiles(dir)?.ToList(); ;
                }

                listFilePathModel.Add(ReadFilePathModel);
            }

            List<ReadFileModel> listModel = new List<ReadFileModel>();
            if (listFilePathModel.Count > 0)
            {
                foreach (ReadFilePathModel pathModel in listFilePathModel)
                {
                    List<string> listFilePath = pathModel.listFilePath;
                    string filePath = listFilePath.Where(a => !a.EndsWith(ConfigManager.suffix)).FirstOrDefault();

                    //LogHelper.Info(JsonXmlUtils.SerializeObject(listFilePath));
                    //string item = listFilePath.FirstOrDefault();
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        // string filePath = item;
                        string fileName = Path.GetFileName(filePath);
                        // 如果时ed结尾的就不要
                        if (fileName.EndsWith(ConfigManager.suffix))
                            continue;

                        ReadFileModel model = new ReadFileModel();
                        model.dirPath = pathModel.readDir;
                        model.fileName = fileName;

                        if (isNetWork)
                        {
                            using (SharedTool tool = new SharedTool(ConfigManager.username, ConfigManager.password, ConfigManager.ip))
                            {
                                model.fileBytes = File.ReadAllBytes(filePath);
                            }
                        }
                        else
                        {
                            model.fileBytes = File.ReadAllBytes(filePath);
                        }

                        listModel.Add(model);
                    }
                }
            }

            return listModel;
        }
    }
}
